/**
 * xiegaolei
 */
import { objectMerge } from '@/utils'

// 递归格式化成多维数组
function listToTreeMulti(list, root = 0, pk = 'id', pid = 'pid', child = 'children', other = null) {
  const tree = []
  if (list) {
    list.forEach(item => {
      if (item[pid] === root) {
        if (other !== null) {
          item = objectMerge(item, other)
        }
        const children = listToTreeMulti(list, item[pk], pk, pid, child, other)
        if (children.length) {
          item[child] = children
        }
        tree.push(item)
      }
    })
  }
  return tree
}

// 递归格式化成一维数组
function listToTreeOne(list, root = 0, prefix = '', pk = 'id', pid = 'pid', str = '|-----', html = 'html', other = null) {
  let tree = []
  let level = 0
  if (list) {
    list.forEach(item => {
      if (item[pid] === root) {
        // 合并其它对象属性
        if (other !== null) {
          item = objectMerge(item, other)
        }
        // 前缀
        if (item[pid] === 0) {
          level = 0
        } else {
          level = getParentsId(list, item[pk], pk, pid).length
        }
        item[html] = str.repeat(level)
        item[html] = item[html] ? (item[html] + prefix) : item[html]
        tree.push(item)
        // 递归
        tree = tree.concat(listToTreeOne(list, item[pk], prefix, pk, pid, str, html, other))
      }
    })
  }
  return tree
}

function getParentsId(list, id, pk = 'id', pid = 'pid') {
  let tree = []
  if (list) {
    list.forEach(item => {
      if (item[pk] === id) {
        tree.unshift(item[pid])
        const parent = getParentsId(list, item[pid], pk, pid)
        if (parent.length) {
          tree = tree.concat(parent)
        }
      }
    })
  }
  return tree
}

// 递归修改值
function upadteArr(arr, attr, val, source) {
  if (arr) {
    arr.map(item => {
      if (item[attr] === val) {
        objectMerge(item, source)
      } else {
        upadteArr(item.children, attr, val, source)
      }
    })
  }
  return arr
}

// 树形递归统计
function getTreeCounts(tree, child = 'children', sum = 'sum') {
  if (tree) {
    for (const item of tree) {
      console.log(item)
      if (item[child].length) {
        item[sum] += getTreeCounts(item, child = 'children', sum = 'sum')
      }
    }
  }
  return tree
}

const tree = {
  listToTreeMulti,
  listToTreeOne,
  getParentsId,
  upadteArr,
  getTreeCounts
}

export default tree

